﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace releaseGrab
{
    public partial class frmReleaseGrab : Form
    {
        private List<String[]> lstMoviesInfo;

        public void setLstMoviesInfo(List<String[]> lstMoviesInfo)
        {
            this.lstMoviesInfo = lstMoviesInfo;
        }

        public List<String[]> getLstMoviesInfo()
        {
            return this.lstMoviesInfo;
        }

        public frmReleaseGrab()
        {
            InitializeComponent();
            lstMoviesInfo = new List<String[]>();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            pbProgressBar.Value = 0;
            dgvTitles.Rows.Clear();
            lstMoviesInfo.Clear();
            Pagina objPaginaInicial = new Pagina();

            if (txtURL.Text.Length > 0)
            {
                int currPage = 1;
                int lastPage = Convert.ToInt32(txtNumPages.Text);
                int progressStep = 100 / lastPage;
                String URL = "";
                HttpWebRequest request = null;
                HttpWebResponse response = null;
                StreamReader reader = null;

                while (currPage <= lastPage)
                {
                    URL = txtURL.Text + "/page/" + currPage + "/";
                    request = (HttpWebRequest)WebRequest.Create(URL);
                    response = (HttpWebResponse)request.GetResponse();

                    //Algumas páginas são comprimidas no server antes do envio
                    //devemos descomprimir essas páginas antes de processá-las
                    if("gzip".Equals(response.ContentEncoding))
                        reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
                    else
                        reader = new StreamReader(response.GetResponseStream());

                    while (!reader.EndOfStream)
                    {
                        objPaginaInicial.sbSource.Append(reader.ReadLine());
                    }

                    lstMoviesInfo.AddRange(retMoviesInfo(objPaginaInicial.sbSource));

                    objPaginaInicial.sbSource.Clear();
                    currPage++;
                    pbProgressBar.Value += progressStep;
                }

                List<String[]>.Enumerator enuPonteiro = lstMoviesInfo.GetEnumerator();

                while (enuPonteiro.MoveNext())
                {
                    dgvTitles.Rows.Add(enuPonteiro.Current);
                }
            }
            else
            {
                MessageBox.Show("Informe a URL!!");
            }
            pbProgressBar.Value = 100;
        }

        private List<String[]> retMoviesInfo(StringBuilder sbSource)
        {
            List<String[]> lstMoviesInfo = new List<String[]>();
            String strSource, strAux, strAuxImage = "";

            String[] arrStrMovieInfo = new String[5];

            strSource = sbSource.ToString();

            //Para cada filme
            while (strSource.IndexOf("rel=\"bookmark\">") >= 0)
            {
                //Pega o título - arrStrMovieInfo[0]
                strAux = strSource.Substring(strSource.IndexOf("rel=\"bookmark\">") + "rel=\"bookmark\">".Length);
                strAuxImage = strAux;
                arrStrMovieInfo[0] = strAux.Substring(0, strAux.IndexOf("</a>")).Trim();
                strSource = strAux.Substring(strAux.IndexOf("</h3>"));

                //Pega a data do post - arrStrMovieInfo[1]
                strAux = strSource.Substring(strSource.IndexOf("Posted on") + "Posted on".Length);
                arrStrMovieInfo[1] = strAux.Substring(0, strAux.IndexOf(" at ")).Trim();
                strSource = strAux.Substring(strAux.IndexOf("<a href"));

                //Pega detalhe - arrStrMovieInfo[3]
                strAux = strSource.Substring(strSource.IndexOf("class=\"entrybody\">", StringComparison.OrdinalIgnoreCase) + "class=\"entrybody\">".Length);
                strAux = strAux.Substring(strAux.IndexOf("</p>", StringComparison.OrdinalIgnoreCase) + "</p>".Length);
                arrStrMovieInfo[3] = strAux.Substring(0, strAux.IndexOf("</a>") + "</a>".Length).Trim();

                //Pega a nota - arrStrMovieInfo[2]
                strAux = strSource.Substring(strSource.IndexOf("IMDB rating:</strong>", StringComparison.OrdinalIgnoreCase) + "IMDB rating:</strong>".Length);
                arrStrMovieInfo[2] = strAux.Substring(0, strAux.IndexOf("/")).Trim();
                strSource = strAux.Substring(strAux.IndexOf("<strong>"));

                //strSource = strAux.Substring(strAux.IndexOf("<a"));

                //Pega a imagem - arrStrMovieInfo[4]
                strAuxImage = strAuxImage.Substring(strAuxImage.IndexOf("src=\"") + "src=\"".Length);
                strAuxImage = strAuxImage.Substring(0, strAuxImage.IndexOf("alt=")).Trim();

                arrStrMovieInfo[4] = strAuxImage.Substring(0, strAuxImage.IndexOf(".jpg") + ".jpg".Length);

                if (validaFiltros(arrStrMovieInfo))
                {
                    lstMoviesInfo.Add(new String[] { arrStrMovieInfo[0], arrStrMovieInfo[1], arrStrMovieInfo[2], arrStrMovieInfo[3], arrStrMovieInfo[4] });
                }
            }

            return lstMoviesInfo;
        }

        private bool validaFiltros(string[] arrStrMovieInfo)
        {
            bool ehValido = true;
            //Se estiver checado para filtrar data e pelo menos uma das duas datas estiver com valor
            if (chkFilterDate.Checked)
            {
                DateTime dtPostedOn = Convert.ToDateTime(arrStrMovieInfo[1]);
                if(!String.IsNullOrEmpty(txbDateFilterFrom.Text))
                {
                    DateTime dtFrom = Convert.ToDateTime(txbDateFilterFrom.Text);
                    if(dtFrom.CompareTo(dtPostedOn) > 0)
                    {
                        ehValido = false;
                    }
                }
                if(!String.IsNullOrEmpty(txbDateFilterTo.Text))
                {
                    DateTime dtTo = Convert.ToDateTime(txbDateFilterTo.Text);
                    if(dtTo.CompareTo(dtPostedOn) < 0)
                    {
                        ehValido = false;
                    }
                }
            }
            float fltScore;
            if (chkImdbScore.Checked)
            {
                if (Single.TryParse(arrStrMovieInfo[2].Replace('.', ','), out fltScore))
                {
                    if (fltScore.CompareTo(Convert.ToSingle(cbxImdbScore.Text)) < 0)
                    {
                        ehValido = false;
                    }
                }
                else
                {
                    if (!chkEhFilmeSemNota.Checked)
                    {
                        ehValido = false;
                    }
                }
            }

            return ehValido;
        }

        private void dgvTitles_CellClick ( object sender, DataGridViewCellEventArgs rowClicked ) {

            dgvTitles.Enabled = false;

            int rowIndex = 0;
            //Pagina objPaginaInicial = new Pagina();

            rowIndex = rowClicked.RowIndex;
            string cellValue = dgvTitles["Title", rowIndex].Value.ToString();

            //Monta Links de Busca
            LinkLabel.Link link = new LinkLabel.Link();
            link.LinkData = "http://thepiratebay.sx/search/" + cellValue + "/0/99/0";
            lnkBuscaPirateBay.Links.Clear();
            lnkBuscaPirateBay.Links.Add(link);

            link = new LinkLabel.Link();
            link.LinkData = "http://torrentz.eu/search?f=" + cellValue;
            lnkBuscaTorrentz.Links.Clear();
            lnkBuscaTorrentz.Links.Add(link);

            //StreamReader reader = null;
            //HttpWebRequest request = null;
            //HttpWebResponse response = null;

            //int currPage = 1;
            //int lastPage = Convert.ToInt32(txtNumPages.Text);
            //String URL = "";

            //while (currPage <= lastPage) {

            //    URL = "http://www.rlslog.net/category/movies/hdrip/page/" + currPage + "/";
            //    request = (HttpWebRequest)WebRequest.Create(URL);
            //    response = (HttpWebResponse)request.GetResponse();

                //Algumas páginas são comprimidas no server antes do envio
                //devemos descomprimir essas páginas antes de processá-las
                //if ("gzip".Equals(response.ContentEncoding))
                //    reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
                //else
                //    reader = new StreamReader(response.GetResponseStream());

                //while (!reader.EndOfStream)
                //{
                //    objPaginaInicial.sbSource.Append(reader.ReadLine());
                //}

                //String strSource, strMovie, strAux = "";

                // detalhes são: nome do filme, endereço da imagem, enredo, gênero, nota IMDB, diretor, estrelando, tamanho, duração, link p/o IMDB
                //String[] arrStrMovieDetail = new String[10];
                //strSource = objPaginaInicial.sbSource.ToString();

                //do {

                //    strAux = strSource.Substring(strSource.IndexOf("rel=\"bookmark\">") + "rel=\"bookmark\">".Length);
                //    strMovie = strAux.Substring(0, strAux.IndexOf("</a>")).Trim();
                //    strSource = strAux.Substring(strAux.IndexOf("</h3>"));

                //    if (strMovie.IndexOf(cellValue) >= 0)
                //    {

                //        List<String[]> lstMovieDetail = retMoviesDetail(objPaginaInicial.sbSource, cellValue);
                //    }

                List<String[]>.Enumerator enuPonteiro = lstMoviesInfo.GetEnumerator();

                    while (enuPonteiro.MoveNext())
                    {
                        if (cellValue.Equals(enuPonteiro.Current[0], StringComparison.OrdinalIgnoreCase))
                        {
                            //rtbDetalheFilme.Enabled = true;
                            //rtbDetalheFilme.Clear();

                            //rtbDetalheFilme.AppendText(enuPonteiro.Current[3]);

                            //rtbDetalheFilme.Enabled = false;
                            String strAntesImg = enuPonteiro.Current[3].Substring(0, enuPonteiro.Current[3].IndexOf("<img"));
                            String strDepoisImg = enuPonteiro.Current[3].Substring(enuPonteiro.Current[3].IndexOf("/>")+2);
                            String strHeader = "<html><head><style type=\"text/css\">*{font-family: \"Verdana, Geneva, sans-serif\";font-size:14px;}</style></head><body>";
                            webBrowser1.DocumentText = strHeader + strAntesImg + strDepoisImg + "</body></html>";
                            pbxDetalheFilme.ImageLocation = enuPonteiro.Current[4];
                        }
                    }

                //} while ( (strSource.IndexOf("rel=\"bookmark\">") >= 0) );

                //currPage++;
                //objPaginaInicial.sbSource.Clear();

            //} 

            tbcPrincipal.SelectedIndex = 2;
            dgvTitles.Enabled = true;
        }


        private List<String[]> retMoviesDetail(StringBuilder sbSource, String movieName) {

            List<String[]> lstMoviesDetail = new List<String[]>();
            String strSource, strMovie, strAux = "";

            int progressStep = 25;
            pbProgressBar.Value = 0;

            // detalhes são: nome do filme, endereço da imagem, enredo, gênero, nota IMDB, diretor, estrelando, tamanho, duração, link p/o IMDB
            String[] arrStrMovieDetail = new String[10];
            strSource = sbSource.ToString();

            do {

                strAux = strSource.Substring(strSource.IndexOf("rel=\"bookmark\">") + "rel=\"bookmark\">".Length);
                strMovie = strAux.Substring(0, strAux.IndexOf("</a>")).Trim();
                strSource = strAux.Substring(strAux.IndexOf("</h3>"));

            } while (strMovie.IndexOf(movieName) < 0);

            // nome
            arrStrMovieDetail[0] = movieName.Trim();

            // imagem
            strAux = strSource.Substring(strSource.IndexOf("src=\"") + "src=\"".Length);
            arrStrMovieDetail[1] = strAux.Substring(0, strAux.IndexOf("alt=")).Trim();

            pbxDetalheFilme.ImageLocation = arrStrMovieDetail[1].Substring(0, arrStrMovieDetail[1].IndexOf(".jpg") + ".jpg".Length);


			//arrStrMovieDetail[1] = strAux.Substring(0, strAux.IndexOf(" \" alt")).Trim();
            strSource = strAux.Substring(strAux.IndexOf("<p><strong>"));

            // enredo - plot ou description
            strAux = strSource.Substring(strSource.IndexOf( "Plot: </strong>", StringComparison.OrdinalIgnoreCase) + "Plot: </strong>".Length );
            arrStrMovieDetail[2] = strAux.Substring(0, strAux.IndexOf("</p>")).Trim();
            strSource = strAux.Substring(strAux.IndexOf("<p><strong>"));

            // gênero
			strAux = strSource.Substring(strSource.IndexOf("</strong>", StringComparison.OrdinalIgnoreCase) + ("</strong>".Length));
            //strAux = strSource.Substring(strSource.IndexOf("Genre: </strong>", StringComparison.OrdinalIgnoreCase) + ("Genre: </strong>".Length)); - antigo funciona
            arrStrMovieDetail[3] = strAux.Substring(0, strAux.IndexOf("<br />")).Trim();
            strSource = strAux.Substring(strAux.IndexOf("<strong>"));

            // IMDB
            strAux = strSource.Substring(strSource.IndexOf("IMDB Rating:</strong>", StringComparison.OrdinalIgnoreCase) + ("IMDB Rating:</strong>".Length));
            arrStrMovieDetail[4] = strAux.Substring(0, strAux.IndexOf("/10")).Trim();
            strSource = strAux.Substring(strAux.IndexOf("<strong>"));

            // diretor
            //strAux = strSource.Substring(strSource.IndexOf("Directed by:</strong>", StringComparison.OrdinalIgnoreCase) + ("Directed by:</strong>".Length));
            //arrStrMovieDetail[5] = strAux.Substring(0, strAux.IndexOf("<br />")).Trim();
            //strSource = strAux.Substring(strAux.IndexOf("<strong>"));

            // estrelando
            //strAux = strSource.Substring(strSource.IndexOf("Starring:</strong>", StringComparison.OrdinalIgnoreCase) + ("Starring:</strong>".Length));
            //arrStrMovieDetail[6] = strAux.Substring(0, strAux.IndexOf("</p>")).Trim();
            //strSource = strAux.Substring(strAux.IndexOf("/><strong>"));

            // tamanho
           // strAux = strSource.Substring(strSource.IndexOf("Size:</strong>", StringComparison.OrdinalIgnoreCase) + ("Size:</strong>".Length));
           // arrStrMovieDetail[7] = strAux.Substring(0, strAux.IndexOf("<br />")).Trim();
           // strSource = strAux.Substring(strAux.IndexOf("<strong>"));

            // duração
           // strAux = strSource.Substring(strSource.IndexOf("Runtime:</strong>", StringComparison.OrdinalIgnoreCase) + ("Runtime:</strong>".Length));
           // arrStrMovieDetail[8] = strAux.Substring(0, strAux.IndexOf("<br />")).Trim();
           // strSource = strAux.Substring(strAux.IndexOf("<strong>"));

            // link IMDB
           // strAux = strSource.Substring(strSource.IndexOf("Links:</strong> <a href=\"") + ("Links:</strong> <a href=\"".Length));
           // arrStrMovieDetail[9] = strAux.Substring(0, strAux.IndexOf("iMDB")).Trim();
           // strSource = strAux.Substring(strAux.IndexOf("</a>"));

            lstMoviesDetail.Add(new String[] { arrStrMovieDetail[0], arrStrMovieDetail[1], arrStrMovieDetail[2], arrStrMovieDetail[3], arrStrMovieDetail[4],
			                                   arrStrMovieDetail[5], arrStrMovieDetail[6], arrStrMovieDetail[7], arrStrMovieDetail[8], arrStrMovieDetail[9] });

            rtbDetalheFilme.Enabled = true;
            rtbDetalheFilme.Clear();

            rtbDetalheFilme.AppendText("Nome: " + arrStrMovieDetail[0] + "\r\n\n\n");
            pbProgressBar.Value += progressStep;
            rtbDetalheFilme.AppendText("Enredo: " + arrStrMovieDetail[2] + "\r\n\n\n");
            pbProgressBar.Value += progressStep;
            rtbDetalheFilme.AppendText("Gênero: " + arrStrMovieDetail[3] + "\r\n\n\n");
            pbProgressBar.Value += progressStep;
            rtbDetalheFilme.AppendText("IMDB: " + arrStrMovieDetail[4] + "\r\n\n\n");
            pbProgressBar.Value += progressStep;
            //rtbDetalheFilme.AppendText("Diretor: " + arrStrMovieDetail[5] + "\r\n\n\n");
            //rtbDetalheFilme.AppendText("Estrelando: " + arrStrMovieDetail[6] + "\r\n\n\n");
           // rtbDetalheFilme.AppendText("Tamanho: " + arrStrMovieDetail[7] + "\r\n\n\n");
            //rtbDetalheFilme.AppendText("Duração: " + arrStrMovieDetail[8] + "\r\n\n\n");
           // rtbDetalheFilme.AppendText("Link IMDB: " + arrStrMovieDetail[9] + "\r\n\n\n");

            rtbDetalheFilme.Enabled = false;
            return lstMoviesDetail;

        }

        private void dgvTitles_MouseHover(object sender, EventArgs e)
        {

            this.Cursor = Cursors.Hand;

        }

        private void dgvTitles_MouseLeave(object sender, EventArgs e)
        {

            this.Cursor = Cursors.Arrow;

        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void chkImdbScore_CheckedChanged(object sender, EventArgs e)
        {
            if (chkImdbScore.Checked)
            {
                chkEhFilmeSemNota.Enabled = true;
            }
            else
            {
                chkEhFilmeSemNota.Checked = false;
                chkEhFilmeSemNota.Enabled = false;
            }
        }

        private void tbpDetalhe_Click(object sender, EventArgs e)
        {

        }

        private void lnkBuscaTorrentz_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(e.Link.LinkData as string);
        }

        private void lnkBuscaPirateBay_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(e.Link.LinkData as string);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            tbcPrincipal.SelectedIndex = 0;
        }

    }
}
